<template>
	<view class="edit_info">
		<view class="info" v-if="!edit.show">
			<view class="header flex justify-center align-center p-3">
				<view class="avatar">
					<u-avatar :src="dealImage" :size="150"
						@click="chooseImage()"
					></u-avatar>
				</view>
			</view>
			<u-cell title="昵称" 
				:value="realInfo.nickname == ''? info.nickname : realInfo.nickname"
				@click="changeValue()"
			></u-cell>
		</view>
		<edit v-else
			:placeholder="edit.placeholder"
			:tip="edit.tip"
			:length="edit.length"
			@save="save"
			@cancel="edit.show = false"
		></edit>
		
		
		<view class="save p-2 flex justify-center align-center"
			v-if="!edit.show"
		>
			<view class="btn">
				<u-button type="primary" text="保存资料" shape="circle"
					@click="saveInfo()"
				></u-button>
			</view>
		</view>
		<view class="blank"></view>
	</view>
</template>

<script>
	import { mapState } from 'vuex';
	import {
		mergeBackPath
	} from "@/utils/file.js";
	import {
		chooseImage
	} from "@/utils/tools.js";
	import {
		editUserInfo
	} from "@/api/user.js";
	
	import edit from "./cpn/edit.vue";
	
	export default {
		components: {
			edit
		},
		data() {
			return {
				realInfo: {
					avatar: '',
					nickname: ''
				},
				edit: {
					tip: "~亲，请输入您的新昵称哦！~",
					placeholder: '请输入您的昵称！',
					value: '',
					show: false,
					length: 25
				}
			}
		},
		computed: {
			...mapState({
				info: state => state.user.info
			}),
			dealImage() {
				if(this.realInfo.avatar == '') return mergeBackPath(this.info.avatar);
				else return mergeBackPath(this.realInfo.avatar);
			}
		},
		methods: {
			chooseImage() {
				chooseImage({
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					count: 1
				}).then(res => {
					this.realInfo.avatar = res[0];
				}).catch(err => this.$msg("选择图片失败"))
			},
			changeValue() {
				this.edit.show = true;
			},
			save(value) {
				this.realInfo.nickname = value;
				this.edit.show = false;
			},
			saveInfo() {
				let info = {
					avatar: this.realInfo.avatar == ''? this.info.avatar : this.realInfo.avatar,
					nickname: this.realInfo.nickname == ''? this.info.nickname : this.realInfo.nickname
				}
				// 修改信息成功要通知store更新信息
				editUserInfo(info).then(res => {
					return this.$store.dispatch("user/getUserInfo");
				}).then(res => {
					this.$msg("修改资料成功！");
					this.$go("/pages/user/info/index");
				}).catch(err => this.$msg(err.message));
			}
		}
	}	
</script>

<style lang="scss" scoped>
.edit_info{
	.header{
		.avatar{
			border: 1rpx solid #d0d0d0;
			border-radius: 50%;
			padding: 7rpx;
		}
	}
	.blank{
		width: 100vw;
		height: 150rpx;
	}
	.save{
		position: fixed;
		width: 100vw;
		bottom: 0;
		.btn{
			width: 500rpx;
		}
	}
}	
</style>